class Show < ActiveRecord::Base
  include               GeoKit::Geocoders
  has_many              :photos
  has_many              :videos
  has_many              :songs, :through => :set_lists
  has_many              :set_lists
  has_many              :comments
  has_many              :blog_posts
  validate              :show_ends_after_it_starts
  validates_presence_of :location
  validates_presence_of :street
  validates_presence_of :city
  validates_presence_of :state
  validates_presence_of :zip
  validates_presence_of :start_time
  validates_presence_of :description
  
  before_save           :get_geocoordinates
  
  after_save            :associations_song_ids
  
  before_destroy        :delete_comments
  before_destroy        :delete_set_lists
  
  has_friendly_id       :location, :use_slug => true
  
  def get_geocoordinates
    location        = MultiGeocoder.geocode(self.address)
    self.longitude  = location.lng.to_s
    self.latitude   = location.lat.to_s
  end
  
  def song_ids=(an_array_of_song_ids = [])
    @song_ids = an_array_of_song_ids
  end             
  
  def associations_song_ids
    SetList.find(:all, :conditions => ['show_id = ?', self.id]).each {|set_list| set_list.destroy if @song_ids}
    @song_ids.each {|song_id| SetList.new(:show_id => self.id, :song_id => song_id).save!} unless @song_ids.nil?
  end
  
  def in_the_past?
    self.start_time <= Time.now ? (return true) : (return false)
  end
  
  def show_ends_after_it_starts
    return if self.end_time.nil?
    self.errors.add(:end_time, 'must be after start date') if self.end_time <= self.start_time
  end
  
  def xml
    location = MultiGeocoder.geocode(self.address)
    xml = '<?xml version="1.0"?>' + "\n"
    xml << "<markers>\n"
    xml << "  <marker latitude=\"" + location.lat.to_s + "\" longitude=\"" + location.lng.to_s + "\" city=\"" + self.city + "\" country=\"United States\" location=\"" + self.street + ", " + self.city + " " + self.state + " " + self.zip + "\" html=\"Come see me perfom at " + self.location + "!\" />\n"
    xml << "</markers>\n"
    return xml
  end
  
  def address
    return String.new(self.street + ", " + self.city + ", " + self.state + " " + self.zip)
  end

protected
  def delete_comments
    self.comments.each {|comment| comment.destroy}
  end
  
  def delete_set_lists
    self.set_lists.each {|set_list| set_list.destroy}
  end
end
